package com.shengruan.user.action;

import java.util.List;

import com.shengruan.admin.vo.Question;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shengruan.admin.jdbc.UserJdbc;
import com.shengruan.admin.util.MessageUtil;
import com.shengruan.admin.vo.User;
import com.shengruan.common.Constants;
import com.shengruan.common.Function;
import com.shengruan.framework.action.ActionSupport;
import com.shengruan.framework.util.AuthFactory;
import com.shengruan.user.jdbc.QuestionAnswerJdbc;
import com.shengruan.admin.jdbc.QuestionJdbc;
import com.shengruan.user.vo.QuestionAnswer;

public class UserForgotPasswordAction extends ActionSupport {

    Logger logger = LoggerFactory.getLogger(getClass());

    private UserJdbc userJdbc = (UserJdbc) this.getJdbc(UserJdbc.class);

    private QuestionJdbc questionJdbc = (QuestionJdbc) this.getJdbc(QuestionJdbc.class);
    private QuestionAnswerJdbc questionAnswerJdbc = (QuestionAnswerJdbc) this.getJdbc(QuestionAnswerJdbc.class);





    @Override
    public void execute() throws Exception {
        String questionId = this.input("questionId1");
        String questionId2 = this.input("questionId2");
        String questionAnswer = this.input("questionAnswer");
        String questionAnswer2 = this.input("questionAnswer2");
        String mobile = this.input("mobile");
        String email = this.input("email");
        String code = this.input("code");

        User user = null;
        String questionCustomize1 = null;
        String questionCustomize2 = null;


        if (StringUtils.isEmpty(mobile) && StringUtils.isEmpty(email)) {
            setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2);
            this.setRequest(Constants.MESSAGE, "请输入手机号码/电子邮件.");
            this.forward("/forgot-password.jsp");
            return;
        }

        //校验验证码
        String validateCode = (String) this.request.getSession().getAttribute("validateCode");
        if (StringUtils.isEmpty(validateCode) || !code.equalsIgnoreCase(validateCode)) {
            setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2);
            this.setRequest(Constants.MESSAGE, "验证码不正确");
            this.forward("/forgot-password.jsp");
            return;
        }

        if (StringUtils.isNotEmpty(email)) {
            user = userJdbc.getByEmail(email);
        }

        if (StringUtils.isNotEmpty(mobile)) {
            user = this.userJdbc.getByMobile(mobile);
        }

        if (null == user) {
            setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2);
            this.setRequest(Constants.MESSAGE, "您输入的用户不存在");
            this.forward("/forgot-password.jsp");
            return;
        }


        if ("-1".equals(questionId)) {
            /*questionCustomize1 = this.input("questionCustomize1");
            Question question = this.questionJdbc.getByName(user.getId(), questionCustomize1);
            if (null == question) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "您输入的第一个自定义问题不存在");
                this.forward("/forgot-password.jsp");
                return;
            } else {
                questionId = question.getId().toString();
            }*/
        }

        if ("-1".equals(questionId2)) {
            questionCustomize2 = this.input("questionCustomize2");
            /*Question question = this.questionJdbc.getByName(user.getId(), questionCustomize2);
            if (null == question) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "您输入的第二个自定义问题不存在");
                this.forward("/forgot-password.jsp");
                return;
            } else {
                questionId2 = question.getId().toString();
            }*/
        }


        if (StringUtils.isNotEmpty(mobile)) {

            QuestionAnswer questionAnswerM1 = this.questionAnswerJdbc.getByQuestionAndMobile(Integer.valueOf(questionId), StringUtils.trim(mobile));
            if (null == questionAnswerM1) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第1个问题选择错误");
                this.forward("/forgot-password.jsp");
                return;
            }

            if (!questionAnswerM1.getAnswer().equals(StringUtils.trim(questionAnswer))) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第1个问题答案输入错误");
                this.forward("/forgot-password.jsp");
                return;
            }

            QuestionAnswer questionAnswerM2 = this.questionAnswerJdbc.getByQuestionAndMobile(Integer.valueOf(questionId2), StringUtils.trim(mobile));
            if (null == questionAnswerM2) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第2个问题选择错误");
                this.forward("/forgot-password.jsp");
                return;
            }

            if (!questionAnswerM2.getAnswer().equals(StringUtils.trim(questionAnswer2))) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第2个问题答案输入错误");
                this.forward("/forgot-password.jsp");
                return;
            }
        }

        if (StringUtils.isNotEmpty(email)) {
            QuestionAnswer questionAnswerM1 = this.questionAnswerJdbc.getByQuestionAndEmail(Integer.valueOf(questionId), StringUtils.trim(email));
            if (null == questionAnswerM1) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第1个问题选择错误");
                this.forward("/forgot-password.jsp");
                return;
            }

            if (!questionAnswerM1.getAnswer().equals(StringUtils.trim(questionAnswer))) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第1个问题答案输入错误");
                this.forward("/forgot-password.jsp");
                return;
            }

            QuestionAnswer questionAnswerM2 = this.questionAnswerJdbc.getByQuestionAndEmail(Integer.valueOf(questionId2), StringUtils.trim(email));
            if (null == questionAnswerM2) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第2个问题选择错误");
                this.forward("/forgot-password.jsp");
                return;
            }

            if (!questionAnswerM2.getAnswer().equals(StringUtils.trim(questionAnswer2))) {
                setParameterAttribute(mobile, email, questionId, questionId2, questionAnswer, questionAnswer2, questionCustomize1, questionCustomize2);
                this.setRequest(Constants.MESSAGE, "第2个问题答案输入错误");
                this.forward("/forgot-password.jsp");
                return;
            }
        }


        //如果用户email不为空，这需要给用户发送邮件来找回密码
        if (StringUtils.isNotEmpty(email)) {
            MessageUtil.sendEmail(email, "密码找回", this.getEmailContent(user.getUserName(), AuthFactory.decryptPassword(user.getPassword())));
            this.setRequest(Constants.MESSAGE, "您已经成功申请找回密码，我们将向您的注册邮箱（" + email + "）发送信件，告知下一步操作，请查收！");
        }

        //如果手机号码不为空，则需要给用户发送手机短信息来找回密码
        if (StringUtils.isNotEmpty(mobile)) {
            MessageUtil.sendSMS(mobile, "乐得拍(www.ledepai.com)找回密码：" + Function.decryptPassword(user.getPassword()));
            this.setRequest(Constants.MESSAGE, "用户密码已经发往您的手机，请注意查收！");
        }

        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);

        this.forward("/forgot-password.jsp");
    }

    public void getQuestion() throws Exception {
        String mobile = this.input("mobile");
        String email = this.input("email");
        String code = this.input("code");

        if (StringUtils.isEmpty(mobile) && StringUtils.isEmpty(email)) {
            setParameterAttribute(mobile, email);
            this.setRequest(Constants.MESSAGE, "请输入手机号码/电子邮件.");
            this.forward("/forgot-password.jsp");
            return;
        }

        //校验验证码
        String validateCode = (String) this.request.getSession().getAttribute("validateCode");
        if (StringUtils.isEmpty(validateCode) || !code.equalsIgnoreCase(validateCode)) {
            setParameterAttribute(mobile, email);
            this.setRequest(Constants.MESSAGE, "验证码不正确");
            this.forward("/forgot-password.jsp");
            return;
        }

        User user = null;
        String forgotType = null;
        if (StringUtils.isNotEmpty(email)) {
            user = userJdbc.getByEmail(email);
            forgotType = email;
        }

        if (StringUtils.isNotEmpty(mobile)) {
            user = this.userJdbc.getByMobile(mobile);
            forgotType = mobile;
        }

        if (null == user) {
            setParameterAttribute(mobile, email);
            this.setRequest(Constants.MESSAGE, "请输入手机号码/电子邮件不存在.");
            this.forward("/forgot-password.jsp");
            return;
        }

        List<Question> questionList = this.questionAnswerJdbc.loadAll(user.getId());
        this.setRequest("questionList", questionList);
        this.setRequest("userId", user.getId());
        this.setRequest("forgotType", forgotType);
        this.forward("/forgot-password-answer.jsp");
    }


    public void checkQuestionAnswer() throws Exception {
        String questionId = this.input("questionId1");
        String questionId2 = this.input("questionId2");
        String questionAnswer = this.input("questionAnswer");
        String questionAnswer2 = this.input("questionAnswer2");
        String userId = this.input("userId");
        String forgotType = this.input("forgotType");


        QuestionAnswer questionAnswerOne = this.questionAnswerJdbc.getById(Integer.valueOf(questionId));
        if (!questionAnswerOne.getAnswer().equals(StringUtils.trim(questionAnswer))) {
            setParameterAttribute(questionAnswer, questionAnswer2, userId, forgotType);
            this.setRequest(Constants.MESSAGE, "第1个问题输入答案错误");
            this.forward("/forgot-password-answer.jsp");
            return;
        }

        QuestionAnswer questionAnswerTwo = this.questionAnswerJdbc.getById(Integer.valueOf(questionId2));
        if (!questionAnswerTwo.getAnswer().equals(StringUtils.trim(questionAnswer2))) {
            setParameterAttribute(questionAnswer, questionAnswer2, userId, forgotType);
            this.setRequest(Constants.MESSAGE, "第2个问题输入答案错误");
            this.forward("/forgot-password-answer.jsp");
            return;
        }


        User user = this.userJdbc.getById(Integer.valueOf(userId));
        if (NumberUtils.isDigits(forgotType)) {
            MessageUtil.sendSMS(forgotType, "乐得拍(www.ledepai.com)找回密码：" + Function.decryptPassword(user.getPassword()));
            this.setRequest(Constants.MESSAGE, "用户密码已经发往您的手机，请注意查收！");
        } else {
            MessageUtil.sendEmail(forgotType, "密码找回", this.getEmailContent(user.getUserName(), AuthFactory.decryptPassword(user.getPassword())));
            this.setRequest(Constants.MESSAGE, "您已经成功申请找回密码，我们将向您的注册邮箱（" + user.getEmail() + "）发送信件，告知下一步操作，请查收！");
        }

        this.forward("/forgot-password.jsp");
    }


    /**
     * 设置用户输入的参数
     *
     * @param mobile
     * @param email
     */
    private void setParameterAttribute(String mobile, String email) {
        this.setRequest("mobile", StringUtils.trim(mobile));
        this.setRequest("email", StringUtils.trim(email));
    }

    /**
     * 设置用户输入的参数
     *
     * @param questionAnswer
     * @param questionAnswer2
     * @param userId
     * @param forgotType
     */
    private void setParameterAttribute(String questionAnswer, String questionAnswer2, String userId, String forgotType) {
        this.setRequest("questionAnswer", StringUtils.trim(questionAnswer));
        this.setRequest("questionAnswer2", StringUtils.trim(questionAnswer2));

        List<Question> questionList = this.questionAnswerJdbc.loadAll(Integer.valueOf(userId));
        this.setRequest("questionList", questionList);
        this.setRequest("userId", userId);
        this.setRequest("forgotType", forgotType);
    }


    /**
     * 设置用户输入的参数
     *
     * @param mobile
     * @param email
     * @param questionAnswer
     * @param questionAnswer2
     */
    private void setParameterAttribute(String mobile, String email, String questionId, String questionId2, String questionAnswer, String questionAnswer2) {
        this.setRequest("mobile", StringUtils.trim(mobile));
        this.setRequest("email", StringUtils.trim(email));
        this.setRequest("questionId", StringUtils.trim(questionId));
        this.setRequest("questionId2", StringUtils.trim(questionId2));
        this.setRequest("questionAnswer", StringUtils.trim(questionAnswer));
        this.setRequest("questionAnswer2", StringUtils.trim(questionAnswer2));

        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);
    }

    /**
     * 设置用户输入的参数
     *
     * @param mobile
     * @param email
     * @param questionAnswer
     * @param questionAnswer2
     */
    private void setParameterAttribute(String mobile, String email, String questionId, String questionId2, String questionAnswer, String questionAnswer2, String questionCustomize1) {
        this.setRequest("mobile", StringUtils.trim(mobile));
        this.setRequest("email", StringUtils.trim(email));
        this.setRequest("questionId", StringUtils.trim(questionId));
        this.setRequest("questionId2", StringUtils.trim(questionId2));
        this.setRequest("questionAnswer", StringUtils.trim(questionAnswer));
        this.setRequest("questionAnswer2", StringUtils.trim(questionAnswer2));
        this.setRequest("questionCustomize1", StringUtils.trim(questionCustomize1));

        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);
    }

    /**
     * 设置用户输入的参数
     *
     * @param mobile
     * @param email
     * @param questionAnswer
     * @param questionAnswer2
     */
    private void setParameterAttribute(String mobile, String email, String questionId, String questionId2, String questionAnswer, String questionAnswer2, String questionCustomize1, String questionCustomize2) {
        this.setRequest("mobile", StringUtils.trim(mobile));
        this.setRequest("email", StringUtils.trim(email));
        this.setRequest("questionId", StringUtils.trim(questionId));
        this.setRequest("questionId2", StringUtils.trim(questionId2));
        this.setRequest("questionAnswer", StringUtils.trim(questionAnswer));
        this.setRequest("questionAnswer2", StringUtils.trim(questionAnswer2));
        this.setRequest("questionCustomize1", StringUtils.trim(questionCustomize1));
        this.setRequest("questionCustomize2", StringUtils.trim(questionCustomize2));

        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);
    }

    /**
     * 加载充值界面
     *
     * @throws Exception
     */
    public void load() throws Exception {

        List<Question> questionList = questionJdbc.loadAll();
        this.setRequest("questionList", questionList);
        this.forward("/forgot-password.jsp");
    }


    /**
     * check by mobile
     *
     * @throws Exception
     */
    public void checkMobile() throws Exception {
        String mobile = this.input("mobile");
        User user = userJdbc.getByMobile(mobile);
        if (null == user) {
            this.print("false");
        } else {
            this.print("true");
        }
    }

    /**
     * @throws Exception
     */
    public void checkEmail() throws Exception {
        String email = this.input("email");
        User user = userJdbc.getByEmail(email);
        if (null == user) {
            this.print("false");
        } else {
            this.print("true");
        }
    }

    /**
     * 拼装email 内容
     *
     * @return
     */
    private String getEmailContent(String userName, String password) {
        StringBuilder sb = new StringBuilder();
        sb.append(userName);
        sb.append(",\n");
        sb.append("   这封 E-mail 来自 http://www.ledepai.com .\n");
        sb.append("\n");
        sb.append("   您收到这封 E-mail 是因为您在 VeryCD.com 使用了忘记密码的功能.\n");
        sb.append("\n");
        sb.append("   ------------------------------------------------\n");
        sb.append("   重    要!\n");
        sb.append("   ------------------------------------------------\n");
        sb.append("\n");
        sb.append("   如果您没有使用忘记密码的功能.绝对不要进行下去.\n");
        sb.append("   并请删除这封 E-mail.\n");
        sb.append("\n");
        sb.append("   只有在您希望使用忘记密码功能的时候需按照下面的提示操作.\n");
        sb.append("\n");
        sb.append("   ------------------------------------------------\n");
        sb.append("   以下是激活指示\n");
        sb.append("   ------------------------------------------------\n");
        sb.append("\n");
        sb.append("   我们要求对您使用忘记密码功能做\"确认\"以确定您有进行这个操作。\n");
        sb.append("   这是为了避免垃圾邮件以及蓄意的滥用.\n");
        sb.append("\n");
        sb.append("   如果在浏览器中没有看到表单,请点击下面的联接.\n");
        sb.append("\n");
        sb.append("   http://www.ledepai.com\n");
        sb.append("\n");
        sb.append("   (AOL E-mail 的用户可能需要将此连接复制到浏览器).\n");
        sb.append("\n");
        sb.append("   它将会询问您的用户 ID,以及您的验证代码.您需要的资料如下:\n");
        sb.append("\n");
        sb.append("   用户 名: " + userName);
        sb.append(userName);
        sb.append("\n\n");
        sb.append("   用户密码: ");
        sb.append(password);
        sb.append("\n\n");
        sb.append("   请复制,或者输入这些到相应表单的位置,并且重新设置您的新密码.\n");
        sb.append("\n");
        sb.append("   一旦完成这个操作,您将可以使用您的新密码(刚才设置的)登录,您可以\n");
        sb.append("   在任何时候通过个人控制台更改您的密码.");
        return sb.toString();
    }
}
